package com.example.afinal;

import android.os.Bundle;
import android.util.Log;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;

public class MainActivity2 extends AppCompatActivity {

    private RecyclerView recyclerView;
    private ProvinceAdapter adapter;
    private List<Province> provinceList;

    private static final String API_URL = "http://guolin.tech/api/china";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        recyclerView = findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        provinceList = new ArrayList<>();

        fetchProvinceData();
    }

    private void fetchProvinceData() {
        JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, API_URL, null,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        try {
                            for (int i = 0; i < response.length(); i++) {
                                JSONObject provinceObject = response.getJSONObject(i);
                                String provinceName = provinceObject.getString("name");
                                String provinceCode = provinceObject.getString("id");
                                Province province = new Province(provinceName, provinceCode);
                                provinceList.add(province);
                            }

                            adapter = new ProvinceAdapter(provinceList);
                            recyclerView.setAdapter(adapter);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e("MainActivity", "Error: " + error.getMessage());
                    }
                });

        VolleySingleton.getInstance(this).addToRequestQueue(request);


    }
}
